<template>
    <component
    is="a-modal"
    v-model:visible="visible"
    :width="960"
    title="复制多场直播"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="handleCopy">
        <a-alert :closable="false" type="info">
            功能说明:先填写第1场的“开始时间“和“上架时间”，再通过智能批量填写完成其他场次设置，新复制的直播可见范围标签和原始直播一致。
        </a-alert>
        <a-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="mt-4">
            <!-- 动态场次列表 -->
            <div v-for="(session, index) in formData.sessions" :key="index">
                    <span>第{{ index + 1 }}场</span>
                    <a-row :gutter="16">
                        <a-col :span="6">
                            <a-form-item label="封面图" field="img_url" label-col-flex="50px">
                                <sa-upload-image-feng v-model="session.img_url" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="18">
                            <a-row :gutter="16">
                                <a-col :span="12">
                                    <a-form-item label="标题" field="subject" label-col-flex="70px">
                                        <a-input v-model="session.subject" placeholder="请输入标题" />
                                    </a-form-item>
                                </a-col>
                                
                               <a-col :span="12">
                                    <a-form-item
                                        label-col-flex="70px"
                                        layout="vertical"
                                        :rules="[{ required: true, message: '请选择开始时间', trigger: 'blur' }]"
                                        label="开始时间"
                                        :prop="`sessions.${index}.startTime`"
                                        style="margin-bottom: 0"
                                    >
                                        <a-date-picker  v-model="session.startTime" show-time value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择开始时间" @ok="(response: any) => (session.startTime = response)" />
                                        
                                    </a-form-item>
                                </a-col>
                                 <a-col :span="12">
                                    <a-form-item
                                        label-col-flex="70px"
                                        layout="vertical"
                                        :rules="[{ required: true, message: '请选择上架时间', trigger: 'blur' }]"
                                        label="上架时间"
                                        :prop="`sessions.${index}.releaseTime`"
                                        style="margin-bottom: 0"
                                    >
                                     <a-date-picker  v-model="session.releaseTime" show-time value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择上架时间" @ok="(response: any) => (session.releaseTime = response)" />
                                       
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-button
                                        v-if="formData.sessions.length > 1"
                                        type="primary"
                                        @click="removeSession(index)"
                                    >
                                        删除
                                    </a-button>     
                                </a-col>
                            </a-row>
                        </a-col>
                    </a-row>
                </div>
                <a-row >
                    <a-col :span="9">
                        <a-form-item label="每场间隔" prop="batchInterval" label-col-flex="70px">
                            <a-space>
                                <a-input-number style="width: 100%" v-model="batchInterval" :min="0" />
                                分钟
                            </a-space>
                        </a-form-item>
                    </a-col>
                     <a-col :span="12">
                        <a-form-item  label-col-flex="0px">
                            <a-button
                                type="primary"
                                :disabled="!batchInterval"
                                @click="handleBatchFill"
                            >
                                智能批量填写
                            </a-button>
                        </a-form-item>
                     </a-col>
                    
                </a-row>

            <a-button link @click="addSession" class="mt-2">
                <sa-icon icon="IconPlus" :size="18"></sa-icon> 添加更多场次
            </a-button>
        </a-form>
    </component>
</template>

<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import { ref, defineEmits, nextTick, computed } from 'vue'
import API from '@/api/live/live'

const emits = defineEmits(['close', 'success'])
const formItemLayout= {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
        lg: { span: 4 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
    },
}
const loading = ref(false)
const visible = ref(false)
const roomData = ref<any>({})
const batchInterval = ref(1 * 60) // 默认间隔1小时
const formRef = ref(null)

const multipleTableRef = ref()
const confirmLoading = ref(false)

// 场次数据 - 动态管理
const formData = ref({
    sessions: [{ subject: '', startTime: null, releaseTime: null, img_url: '' }]
})

// 表单验证规则
const rules = ref<any>({})

// 打开弹窗并初始化数据
const open = (item: any) => {
    visible.value = true
    roomData.value = { ...item }

    // 从roomData填充第一场数据
    if (item) {
        formData.value.sessions[0] = {
            subject: item.name || '',
            startTime: null,
            releaseTime: null,
            img_url: item.cover || ''
        }
    }
}

// 添加场次
const addSession = () => {
    // 最大10场
    if (formData.value.sessions.length >= 10) {
        return  Message.error('最多添加10场直播')
    }
    formData.value.sessions.push({
        subject: '',
        startTime: null,
        releaseTime: null,
        img_url: ''
    })

    // 触发表单验证更新
    nextTick(() => {
        if (formRef.value) {
            formRef.value.clearValidate()
        }
    })
}

// 删除场次
const removeSession = (index: number) => {
    if (formData.value.sessions.length <= 1) {
        return Message.error('至少保留一场直播')
    }
    formData.value.sessions.splice(index, 1)

    // 触发表单验证更新
    nextTick(() => {
        if (formRef.value) {
            formRef.value.clearValidate()
        }
    })
}

// 智能批量填写
const handleBatchFill = () => {
    const firstSession = formData.value.sessions[0]
    if (
        !firstSession.subject ||
        !firstSession.img_url ||
        !firstSession.startTime ||
        !firstSession.releaseTime
    ) {
        return Message.error('请先填写第1场的标题、封面图、开始时间和上架时间')
    }

    if (formData.value.sessions.length < 2) {
        return Message.error('请先添加场次')
    }
    // 转换为时间戳进行计算
    const firstStartTime = new Date(firstSession.startTime).getTime()
    const firstReleaseTime = new Date(firstSession.releaseTime).getTime()
    const intervalMs = batchInterval.value * 60 * 1000

    // 从第二场开始填充
    for (let i = 1; i < formData.value.sessions.length; i++) {
        formData.value.sessions[i].subject = firstSession.subject
        formData.value.sessions[i].startTime = new Date(firstStartTime + i * intervalMs)
        formData.value.sessions[i].releaseTime = new Date(firstReleaseTime + i * intervalMs)
        formData.value.sessions[i].img_url = firstSession.img_url
    }

    Message.success('已自动填充后续场次时间设置')
}

// 确认复制
const handleCopy = async () => {
    // 验证所有场次
    if (!formRef.value) return

    // 触发表单验证更新
    await formRef.value.validate()

    // 验证通过，继续提交逻辑
    try {
        confirmLoading.value = true
        // 为每个场次创建复制数据
        const copyDataList = formData.value.sessions.map((session) => ({
            start_time: session.startTime,
            list_show_time: session.releaseTime,
            name: session.subject,
            cover: session.img_url
        }))
        const params = {
            copy_room_id: roomData.value.room_id,
            copy_list: JSON.stringify(copyDataList)
        }

        console.log('复制数据:', params)
        await API.swcopyRoom(params)
        // feedback.msgSuccess('复制成功')
        emits('success')
        close()
    } catch (error) {
        // feedback.msgError('复制失败，请重试')
    } finally {
        setTimeout(() => {
            confirmLoading.value = false
        }, 500)
    }
}

// 关闭弹窗
const close = () =>{
    visible.value = false
     formData.value.sessions = [
        {
            subject: '',
            startTime: null,
            releaseTime: null,
            img_url: ''
        }
    ]
    if (multipleTableRef.value) {
        multipleTableRef.value.clearSelection()
    }
}


defineExpose({
    open
})
</script>

<style scoped lang="less">
::v-deep .el-dialog__body {
    padding: 20px;
    max-height: 500px;
    overflow-y: auto;
}

::v-deep .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

::v-deep .el-upload:hover {
    border-color: var(--el-color-primary);
}

::v-deep .el-input-number .el-input__inner {
    text-align: center !important;
}
</style>
